<template>
  <div class="app-container">
    <el-form :model="purchaseOrderForm" :rules="purchaseOrderFormRules" ref="purchaseOrderForm" label-width="160px" class="demo-ruleForm" label-position="right">
      <el-row>
        <el-input type="hidden" v-model="purchaseOrderForm.id" disabled></el-input>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="采购单编号" prop="sn">
            <el-input v-model="purchaseOrderForm.sn" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="purchaseOrderForm.supplierId" :disabled="disable" clearable filterable placeholder="请选择供应商">
              <el-option
                v-for="dict in supplierOptions"
                :key="dict.id"
                :label="dict.supplierName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="购货日期">
            <el-form-item prop="buyDate">
              <el-date-picker clearable type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="purchaseOrderForm.buyDate" :disabled="disable"></el-date-picker>
            </el-form-item>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单据日期">
            <el-form-item prop="billDate">
              <el-date-picker clearable type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="purchaseOrderForm.billDate" :disabled="disable"></el-date-picker>
            </el-form-item>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="purchaseOrderForm.remark" :disabled="disable"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="商品信息">
        <el-button type="primary" icon="el-icon-plus" plain size="mini" v-if="!disable" @click="selectProducts">选择商品</el-button>
        <el-dialog  :visible.sync="open" title="商品列表" width="800px">
          <select-product v-on:productList="getProductList"/>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="enterSelectProducts">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
        <el-table show-summary :summary-method="getSummaries"
          :data="purchaseOrderForm.purchaseOrderItemList"
          style="width: 100%; margin: 15px 0 0 0;"  stripe
          >
          <el-table-column
            label="商品名称"
            prop="product.productName">
            <template slot-scope="{row,$index}">
              <span>{{row.product.productName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="商品规格"
            prop="productSku.specifications">
            <template slot-scope="{row,$index}">
              <span>{{row.productSku.specifications}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="商品条码"
            prop="productSku.barCode">
            <template slot-scope="{row,$index}">
              <span>{{row.productSku.barCode}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="购买单价(元)"
            prop="price">
            <template slot-scope="{row,$index}">
              <el-input type="number" v-model="row.price" :disabled="disable"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="购买数量"
            prop="qty">
            <template slot-scope="{row,$index}">
              <el-input type="number" v-model="row.qty" :disabled="disable"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="商品单位"
            prop="product.unit">
            <template slot-scope="scope">
              <span>{{unitFormat(scope.row.product.unit)}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="采购金额(元)"
            prop="amount">
            <template slot-scope="scope">
              {{ scope.row.amount = multiply(scope.row, scope.$index) }}
            </template>
          </el-table-column>
          <el-table-column
            label="仓库"
            prop="warehouseId">
            <template slot-scope="{row,$index}">
              <el-select v-model="row.warehouseId" :disabled="disable" clearable filterable placeholder="请选择供应仓库">
                <el-option
                  v-for="dict in warehouseOptions"
                  :key="dict.id"
                  :label="dict.warehouseName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            align="right"
            width="100px"
            v-if="!disable">
            <template slot-scope="scope">
              <el-button type="danger" size="mini" plain icon="el-icon-delete"   @click.native="handleDelete(scope.$index, scope.row)" >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item style="margin-top: 100px" v-if="!disable">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>
<script>
import { getPurchase, savePurchase } from "@/api/oms/purchaseOrder";
import { listProductDto } from "@/api/oms/product";
import { listAllSupplier } from "@/api/oms/supplier";
import { listAllWarehouse } from "@/api/oms/warehouse";
import SelectProduct from "../../../components/product";

export default {
  name: "PurchaseOrderEdit",
  components: {SelectProduct},
  data() {
    return {
      showEdit: [], //显示编辑框
      showBtn: [],
      search: '',
      // 当未入库都可以操作
      disable: false,
      // 供应商
      supplierOptions: [],
      //单位
      unitOptions: [],
      // 仓库
      warehouseOptions: [],
      // 商品列表
      productList: [],
      // 默认关闭
      open: false,
      purchaseOrderForm: {},
      purchaseOrderFormRules: {}
    };
  },
  created() {
    const id = this.$route.params.id
    if(id) {
      getPurchase(id).then(response => {
        this.purchaseOrderForm = response.data
        if (this.purchaseOrderForm.inventoryStatus == 1) {
            this.disable = true
        }
      });
    }
    // 查询供应商信息
    listAllSupplier().then(res =>{
      this.supplierOptions = res.data
    });

    // 查询仓库信息
    listAllWarehouse().then(res =>{
       this.warehouseOptions = res.data
    });

    // 单位字典
    this.getDicts("unit").then(response => {
      this.unitOptions = response.data;
    });
  },


  computed:{
    totalAmount () {
      console.log("dfefeffefefe")
      return 0.01
},
  },

  methods: {
    submitForm() {
      this.$refs.purchaseOrderForm.validate((valid) => {
        if (valid) {
          savePurchase(this.purchaseOrderForm).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg);
              this.close();
            }
          });
        } else {
          this.msgError("表单校验未通过，请重新检查提交内容");
        }
      });
    },
    /** 字典状态字典翻译 */
    unitFormat(val) {
      return this.selectDictLabel(this.unitOptions, val);
    },
    // 重置表单
    resetForm() {
      this.purchaseOrderForm.purchaseOrderItemList = []
      this.$refs.purchaseOrderForm.resetFields();
    },
    //点击删除
    handleDelete(index, row) {
      this.purchaseOrderForm.purchaseOrderItemList.splice(index, 1)
    },
    // 选择商品
    selectProducts() {
     this.open = true
    },
    // 获取商品列表
    getProductList(data) {
      console.log("getProductList", data)
      this.productList = data
    },
    // 确定选择商品
    enterSelectProducts(){
      let poList  = this.purchaseOrderForm.purchaseOrderItemList
      if (!poList) {
        poList = []
        this.purchaseOrderForm.purchaseOrderItemList = poList
      }
      this.productList.forEach(function (item) {
        let o ={product:{}, productSku:{}};
        o.skuId = item.id
        o.productId = item.productId
        o.product.productName = item.productName
        o.productSku.specifications = item.specifications
        o.productSku.barCode = item.barCode
        o.product.unit = item.unit
        poList.push(o)
      })
      console.log('poList', poList)
      this.open = false
    },
    // 相乘
    multiply(row,index) {
      if(row.qty && row.price){
        row.amount = Number(row.qty)*Number(row.price)
      }
      return row.amount
    },

    //自定义统计
    getSummaries(param) {
      const { columns, data } = param;//这里可以看出，自定义函数会传入每一列，以及数据
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        //页面分别统计 处理
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr ;
            } else {
              return prev;
            }
          }, 0);

          //console.log("sums[index]=="+sums[index])
          //此处结合了方式一的判断处理，实现多种条件处理
          switch(column.property) {
            case "amount":
              this.purchaseOrderForm.totalAmount = sums[index]
              return sums[index];
              break;
            default:
              return sums[index] = '';
              break;
          }
        } else {
          sums[index] = ''; //如果列的值有一项不是数字，就显示这个自定义内容
        }
      });
      return sums;//最后返回合计行的数据
    },

    // 取消对话框
    cancel(){
      this.open = false;
    },

    /** 关闭按钮 */
    close() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/purchase/purchase", query: { t: Date.now()}})
    }
  }
}
</script>
